package com.washmadam.service.service.customer.impl;

import java.util.Date;
import java.util.List;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.washmadam.service.common.enums.DeleteEnum;
import com.washmadam.service.common.enums.StatusEnum;
import com.washmadam.service.db.dao.CustomerMapper;
import com.washmadam.service.db.dao.CustomerMapperSpec;
import com.washmadam.service.db.dto.Customer;
import com.washmadam.service.db.example.CustomerExample;
import com.washmadam.service.db.request.operate.CustomerOrderOperateParam;
import com.washmadam.service.service.customer.CustomerOperateService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class CustomerOperateServiceImpl implements CustomerOperateService {
	@Autowired
	private CustomerMapper customerMapper;
	@Autowired
	private CustomerMapperSpec customerMapperSpec;

	@Override
	public Customer saveAndGetCustomer(CustomerOrderOperateParam requestParam) {
		CustomerExample example = new CustomerExample();
		example.createCriteria()
			   .andContactMobileEqualTo(requestParam.getContactMobile())
		       .andStatusEqualTo(StatusEnum.ENABLE.getCode())
			   .andIsDeleteEqualTo(DeleteEnum.NORMAL.getCode());
		example.setOrderByClause(" id desc");
		List<Customer> customerList =customerMapper.selectByExample(example);
		if(CollectionUtils.isNotEmpty(customerList)) {
			return customerList.get(0);
		}
		Customer customer = new Customer();
		BeanUtils.copyProperties(requestParam, customer);
		if(requestParam.getHandleDate()==null) {
			customer.setHandleDate(new Date());
		}
		customer.setServiceNum(0);
		customer.setId(null);
		customerMapper.insertSelective(customer);
		return customer;
	}

	@Override
	public void addServiceNum(Long customerId, Integer num) {
		customerMapperSpec.updateServiceNum(customerId,num);
	}

}
